package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysOrgChildren;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.util.SubSystemUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 组织管理controller
 * @author nd
 */
@Controller
@Action(ownermodel = SysAuditModelType.ORG_MANAGEMENT)
@RequestMapping(UrlConstants.PROJECT_ROOT+UrlConstants.PROJECT_MODULE_SYSTEM+"/sysOrg")
public class SysOrgController extends SysBaseController {

    @Resource
    private SysOrgService sysOrgService;

    /**
     * 新增或修改组织
     * @param sysOrg 组织
     * @return ResultData
     */
    @Action(description = "编辑组织信息",
            detail = "<#if StringUtil.isEmpty(sysOrg.orgId)>添加<#else>更新</#if>组织【${sysOrg.orgName}】<#if success>成功<#else>失败</#if>",
            exectype = "编辑日志")
    @PostMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @ResponseBody
    public ResultData save(HttpServletRequest request,SysOrg sysOrg){
        SysOrg finalSysOrg = new SysOrg();
        finalSysOrg.setOrgId(sysOrg.getOrgId());
        finalSysOrg.setOrgName(sysOrg.getOrgName());
        SysAuditThreadLocalHolder.putParamerter("sysOrg", finalSysOrg);
        try {
            /*
            判断组织名称是否已存在
             */
            boolean isExists = sysOrgService.isExistsOrgName(sysOrg.getOrgName(),sysOrg.getOrgId());
            if(isExists){
                return getResultDataError("add.org.failure.exist.orgName");
            }
            /*
            判断组织代码是否已存在
             */
            isExists = sysOrgService.isExistsOrgCode(sysOrg.getCode(),sysOrg.getOrgId());
            if(isExists){
                return getResultDataError("add.org.failure.exist.orgCode");
            }
            String systemId = SubSystemUtil.getCurrentSystemId(request);
            sysOrgService.save(sysOrg,systemId);
        }catch (Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return  getResultDataError("save.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return  getResultDataSuccess("save.success");
    }

    /**
     * 删除组织
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "删除组织信息",
            detail = "删除组织【${orgName}】<#if success>成功<#else>失败</#if>",
            exectype = "删除日志")
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    public ResultData delById(HttpServletRequest request){
            String orgId = RequestUtil.getString(request, "orgId");
            SysOrg sysOrg = sysOrgService.getOneById(orgId);
            SysAuditThreadLocalHolder.putParamerter("orgName", sysOrg.getOrgName());
        try {
            String systemId = SubSystemUtil.getCurrentSystemId(request);
            if(orgId == null){
                return getResultDataError("delete.failure");
            }
            String result = sysOrgService.delOrgById(orgId,systemId);
            if(null != result){
                return getResultDataError(result);
            }
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return  getResultDataSuccess("delete.success");
    }

    /**
     * 查找组织list树
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "查询组织列表",
            detail = "查询列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    public ResultData list(HttpServletRequest request){
        try {
            /*
             1.查找当前用户所属机构（租户|组织） 根据登录人的租户ID去展示组织树
             */
            String userId = ContextUtil.getCurrentUserId();
            List<SysOrg> sysOrgList = null;
            /*
            超管的用户id是初始化入库的 所有超管id被视为常量
             */
            if(SystemConst.SUPER_ADMIN_ID.equals(userId)){
                sysOrgList = sysOrgService.querySubSysOrgTreeDataBySupOrgId(SystemConst.TOP_ORG_ID);
            }else{
                String belongOrgId = sysOrgService.getOrgByUserId(userId)!=null ? sysOrgService.getOrgByUserId(userId).getOrgId():SystemConst.TOP_ORG_ID;
                sysOrgList = sysOrgService.querySysOrgTreeDataByOrgId(belongOrgId);
            }
            int count = sysOrgList==null?0:sysOrgList.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",count,sysOrgList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 查找组织list树
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "查询所有组织列表",
            detail = "查询列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/listAll")
    @ResponseBody
    public ResultData listAll(HttpServletRequest request){
        try {
            List<SysOrg> sysOrgList = sysOrgService.queryAll();
            int count = sysOrgList==null?0:sysOrgList.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",count,sysOrgList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }


    @Action(description = "查询带有children的组织列表",
            detail = "查询带有children的列表<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/treeSelectOrg")
    @ResponseBody
    public ResultData treeSelectOrg(HttpServletRequest request){
        try {
            /*
             1.查找当前用户所属机构（租户|组织） 根据登录人的租户ID去展示组织树
             */
            String userId = ContextUtil.getCurrentUserId();
            List<SysOrgChildren> sysOrgList = null;
            /*
            超管的用户id是初始化入库的 所有超管id被视为常量
             */
            if(SystemConst.SUPER_ADMIN_ID.equals(userId)){
                sysOrgList = sysOrgService.querySubSysOrgTreeDataBySupOrgIdToTree(SystemConst.TOP_ORG_ID);
            }else{
                String belongOrgId = sysOrgService.getOrgByUserId(userId)!=null ? sysOrgService.getOrgByUserId(userId).getOrgId():SystemConst.TOP_ORG_ID;
                sysOrgList = sysOrgService.querySysOrgTreeDataByOrgIdToTree(belongOrgId);
            }
            int count = sysOrgList==null?0:sysOrgList.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",count,sysOrgList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 打开组织排序框 查询要排序的组织list
     * @param request
     * @return
     */
    @Action(description = "打开组织排序框 查询要排序的组织list",
            detail = "查询组织<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/listForSort")
    @ResponseBody
    public ResultData listForSort(HttpServletRequest request){
        try {
            String orgId = RequestUtil.getString(request,"orgId");
            List<SysOrg> list = sysOrgService.querySubSysOrgBySupOrgIdNoChild(orgId);
            int count = list==null?0:list.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",count,list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 组织管理页 根据当前用户 查找其所在租户下组织list
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "组织管理页 根据当前用户 查找其所在租户下组织list",
            detail = "查询组织<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/listFlat")
    @ResponseBody
    public ResultData listFlat(HttpServletRequest request){
        try {
            /*
             1.查找当前用户所属机构（租户|组织） 根据登录人的租户ID去展示组织树
             */
            String paramPath;
            List<SysOrg> sysOrgList = new ArrayList<>();
            if(SystemConst.SUPER_ADMIN_ID.equals(ContextUtil.getCurrentUserId())){
                paramPath = SystemConst.TOP_ORG_ID;
                sysOrgList.add(sysOrgService.getTopOrg());
            }else{
                SysOrg org = sysOrgService.getOrgByUserId(ContextUtil.getCurrentUserId());
                paramPath = org.getPath();
            }
            sysOrgList.addAll(sysOrgService.queryOrgByPath(paramPath));
            int count = sysOrgList==null?0:sysOrgList.size();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("update.success",count,sysOrgList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("update.failure");
        }
    }

    /**
     * 组织管理页 根据当前用户 查找其所在租户下组织list(可带参数查询)
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "组织管理页 根据当前用户 查找其所在租户下组织list",
            detail = "查询组织<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/listFlatSelector")
    @ResponseBody
    public ResultData listFlatSelector(HttpServletRequest request){
        try {
             /*
             1.查找当前用户所属机构（租户|组织） 根据登录人的租户ID去展示组织树
             */
            String paramPath;
            QueryFilter queryFilter = new QueryFilter(request);
            List<SysOrg> sysOrgList = new ArrayList<>();
            if(SystemConst.SUPER_ADMIN_ID.equals(ContextUtil.getCurrentUserId())){
                paramPath = SystemConst.TOP_ORG_ID;
                sysOrgList.add(sysOrgService.getTopOrg());
            }else{
                SysOrg org = sysOrgService.getOrgByUserId(ContextUtil.getCurrentUserId());
                paramPath = org.getPath();
            }
            queryFilter.put("path",paramPath+ StringPool.PERCENT);
            sysOrgList.addAll(sysOrgService.queryList(queryFilter));
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("update.success",queryFilter.getPageBean().getTotalCount(),sysOrgList);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("update.failure");
        }
    }

    /**
     * 根据组织Id查看组织简介
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "查询组织信息",
            detail = "<#assign entity=sysOrgService.getSysOrgById(orgId)/>查询【${entity.orgName}】信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    public ResultData getSysOrg(HttpServletRequest request){
        try {
            String orgId = RequestUtil.getString(request, "orgId");
            SysOrg sysOrg = sysOrgService.getSysOrgById(orgId);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",1L,sysOrg);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 根据组织编码查询组织信息
     * @param request
     * @return
     */
    @Action(description = "根据组织编码查询组织信息",
            detail = "<#assign entity=sysOrgService.getSysOrgById(orgId)/>根据组织编码查询【${entity.orgName}】信息<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @GetMapping("/getSysOrgByOrgCode")
    @ResponseBody
    public ResultData getSysOrgByOrgCode(HttpServletRequest request){
        try {
            String orgCode = RequestUtil.getString(request,"orgCode");
            SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(orgCode);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success",1L,sysOrg);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }

    }

    /**
     * 给租户分配资源
     * @param request 请求
     * @return ResultData
     */
    @Action(description = "给租户分配资源",
            detail = "<#assign entity=sysOrgService.getSysOrgById(orgId)/>给租户【${entity.orgName}】分配资源<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @PostMapping("/assign")
    @ResponseBody
    public ResultData assignResource(HttpServletRequest request){
        try{
            String systemId=SubSystemUtil.getCurrentSystemId(request);
            String orgId=RequestUtil.getString(request, "orgId");
            String[] resIds=null;
            if(request.getParameter("resIds")!=null && !"".equals(request.getParameter("resIds"))){
                resIds=RequestUtil.getStringAryByStr(request, "resIds");
            }
            sysOrgService.assignResource(orgId,systemId,resIds);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("assign.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("assign.success");
    }

    /**
     * 排序
     * @param request
     * @return
     */
    @Action(description = "给组织排序",
            detail = "组织排序<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    @PostMapping("/sort")
    @ResponseBody
    public ResultData sortOrg(HttpServletRequest request){
        String[] lAryId = RequestUtil.getStringAryByStr(request, "orgIds");
        try{
            sysOrgService.updateSn(lAryId);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("operation.success");
    }


    /**
     * 页面跳转 添加|修改页
     */
    @Action(description = "组织编辑页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/update")
    public String viewAddAndEditPage(HttpServletRequest request , Model model){
        String orgId = RequestUtil.getString(request,"orgId");
        String pid = RequestUtil.getString(request,"pid");
        String isTenant = RequestUtil.getString(request,"isTenant");
        model.addAttribute("orgId",orgId);
        model.addAttribute("pid",pid);
        model.addAttribute("isTenant",isTenant);
        return "sysOrg/update";
    }
    /**
     * 页面跳转 排序
     */
    @Action(description = "组织排序页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/sort")
    public String  viewSort(HttpServletRequest request , Model model){
        String orgId = RequestUtil.getString(request,"orgId");
        model.addAttribute("orgId",orgId);
        return "sysOrg/sort";
    }
    /**
     * 页面跳转 列表页
     */
    @Action(description = "组织列表页面跳转",exectype = "页面跳转日志")
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/list")
    public String viewList(){
        return "sysOrg/list";
    }
}
